package de.tapps.brainstorming;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.widget.EditText;
/**
 * Return the topic title and the content to a specific topic (an id)
 * 
 * @author Timo
 * Decrypted - ok
 */
public class PhoneNumber extends AsyncTask<String, Integer, String> {
	private Crypter crypter;
	private MainActivity activity = new MainActivity();
	private GUI gui;
	public PhoneNumber(MainActivity act){
		activity = act;
		crypter = new Crypter(activity);
	}
	

	@Override
	protected String doInBackground(String... arg0) {
		new Thread(new Runnable() {
			public void run() {
				URL url = null;
				
				try {
					TelephonyManager telephonyManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
					String imei = telephonyManager.getDeviceId();
					url = new URL(
							"http://t-apps-online.de/BrainStorming/savedMail.php?imei="
									+ crypter.encrypt(imei));
					String readLine = null;
					BufferedReader buffReader = new BufferedReader(
							new InputStreamReader(url.openStream()));
					while ((readLine = buffReader.readLine()) != null) {
						if (readLine.equals("0")){
							activity.runOnUiThread(new Runnable() {
								public void run() {
							AlertDialog.Builder alert = new AlertDialog.Builder(activity);

							alert.setTitle("E-Mail Adresse");
							alert.setMessage("Um Brainstorming mit Ihren Kontakten betreiben zu können, müssen Sie Ihre E-Mail Adresse eingeben und anschließend verifizieren.");

							// Set an EditText view to get user input 
							final EditText input = new EditText(activity);
							alert.setView(input);

							alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								
								new AddMail(activity,input.getText().toString()).execute();
							}
							});

							alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
							  public void onClick(DialogInterface dialog, int whichButton) {
									gui.showMessage(""+input.getText());

							    // Canceled.
							  }
							});
							alert.setCancelable(false);
							alert.show();
								}
							});
						}
					}
				} catch (MalformedURLException me) {
					me.printStackTrace();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
				
			}
		}).start();
		return null;
	}
}